package com.zzz.mongo.config;

import com.mongodb.ConnectionString;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.core.MongoAction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;
import org.springframework.data.mongodb.core.WriteConcernResolver;

@Configuration
public class MongodbConfig extends AbstractMongoClientConfiguration implements WriteConcernResolver {

    @Bean
    public MongoTemplate mongoTemplate1() {
        return new MongoTemplate(MongoClients.create(new ConnectionString("mongodb://192.168.1.101:27017")), "mongo");
    }

    @Override
    public MongoClient mongoClient() {
        return MongoClients.create(new ConnectionString("mongodb://192.168.1.101:27017"));
    }

    @Bean
    public MongoTemplate mongoTemplate2() {
        return new MongoTemplate(new SimpleMongoClientDbFactory(MongoClients.create(new ConnectionString("mongodb://192.168.1.101:27017")), "mongo"));
    }

    @Override
    protected String getDatabaseName() {
        return "mongo";
    }

    @Override
    public WriteConcern resolve(MongoAction action) {
        if (action.getEntityType().getSimpleName().contains("user")) {
            return WriteConcern.JOURNALED;
        }
        return action.getDefaultWriteConcern();
    }
}
